<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;


class OrderController extends AdminController {

	public function _initialize() {
		parent::_initialize();
		
	}


	/**
	 * 页面初始化
	 */
	public function index(){
		if(is_login()){
			$mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
			if(intval(is_login())!= 1){
		        if($group['group_id'] == 4){
		        	$this->redirect('Order/adminIndex');
		        }
			}

           $mapa['uid'] = intval(is_login());
	        if(I('value')!==''){
	        	$map['status']=I('value');
	        	$this->assign("val",I('value'));
	        }else{
	        	$map['status']  =   array('egt',0);
	        }
        	$group = M('AuthGroupAccess')->where($mapa)->find();
        	$patient_name = I('patient_name');
	        /*if(is_numeric($patient_name)){
	            $map['id|patient_name']=   array(intval($patient_name),array('like','%'.$patient_name.'%'),'_multi'=>true);
	        }else{
	            $map['patient_name']    =   array('like', '%'.(string)$patient_name.'%');
	        }*/
	        if($patient_name){
	        	$uid=M('member')->where(array('nickname'=>array('like','%'.$patient_name.'%')))->getField('uid',true);
		        $where['uid']=$uid?array('in',$uid):$uid;
		        $where['phone']=array('like','%'.$patient_name.'%');
		        $where['patient_name']=array('like','%'.$patient_name.'%');
		        $where['id']=array('like','%'.$patient_name.'%');
				$where['_logic'] = 'or';
				$map['_complex'] = $where;
			}
	        if(!(intval(is_login()) == 1 || $group['group_id'] == 4)){
	        	$map['uid'] = is_login();	
	        }
	        $list   = $this->lists('Order', $map);
	        int_to_string($list);
        	$list   =   $this->parseDocumentList($list,'5');
	        $this->assign('_list', $list);
	        $this->meta_title = '用户信息';
	        $this->display();
		} else{
			$this->error('请登录', U(''));
		}
    }

    public function adminIndex(){
		if(is_login()){
	        $mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
			if(intval(is_login())!= 1){
		        if($group['group_id'] != 4){
		        	$this->redirect('Order/index');
		        }
			}

	        $mapa['uid'] = intval(is_login());
	        if(I('value')!==''){
	        	$map['status']=I('value');
	        	$this->assign("val",I('value'));
	        }else{
	        	$map['status']  =   array('egt',0);
	        }

        	$group = M('AuthGroupAccess')->where($mapa)->find();
        	$patient_name = I('patient_name');
	        /*if(is_numeric($patient_name)){
	            $map['id|patient_name']=   array(intval($patient_name),array('like','%'.$patient_name.'%'),'_multi'=>true);
	        }else{
	            $map['patient_name']    =   array('like', '%'.(string)$patient_name.'%');
	        }*/
	        if($patient_name){
	        	$uid=M('member')->where(array('nickname'=>array('like','%'.$patient_name.'%')))->getField('uid',true);

		        $where['uid']=$uid?array('in',$uid):$uid;
		        $where['phone']=array('like','%'.$patient_name.'%');
		        $where['patient_name']=array('like','%'.$patient_name.'%');
		        $where['id']=array('like','%'.$patient_name.'%');
				$where['_logic'] = 'or';
				$map['_complex'] = $where;
			}
	        if(!(intval(is_login()) == 1 || $group['group_id'] == 4)){
	        	$map['uid'] = is_login();	
	        }
	        $list   = $this->lists('Order', $map);
	        int_to_string($list);
        	$list   =   $this->parseDocumentList($list,'5');
	        $this->assign('_list', $list);
	        $this->meta_title = '用户信息';
	        $this->display();
		} else{
			$this->error('请登录', U(''));
		}
    }

    /**
     * 增
     */
    public function add($gender = '', $patient_name = '', $old = '', $weight = '', $phone = '', $mhistory = '', $description = '', $data = '', $medicine = '', $regulate_problem = '', $former = '', $images = '', $status = '', $investigate_desc = '', $visit_desc = '', $prescription_desc = '', $price_desc = '', $produc_desc = '', $pack_desc = '', $regoods_desc = '', $address = ''){
    	if(IS_POST){
            if($this->countOrder() == 0){
        		$map['uid'] = is_login();
        		$wakak = M('Member')->where($map)->find();
                if($wakak['point'] > 9000){
		    		$order = array('gender' => $gender, 'patient_name' => $patient_name, 'old' => $old, 'weight' => $weight, 'phone' => $phone, 'mhistory' => $mhistory, 'description' => $description, 'data' => $data, 'medicine' => $medicine, 'regulate_problem' => $regulate_problem, 'former' => $former, 'images' => $images, 'uid' => $map['uid'], 'status' => $status, 'investigate_desc' => $investigate_desc, 'visit_desc' => $visit_desc, 'prescription_desc' => $prescription_desc, 'price_desc' => $price_desc, 'produc_desc' => $produc_desc, 'pack_desc' => $pack_desc, 'regoods_desc' => $regoods_desc, 'address' => $address);
		    		if(!M('Order')->add($order)){
	    				$this->error('新增订单失败！', U('index'));
		    		} else {
		    			$user['point'] = array('exp','point-9000');
		    			$user['repoint'] = array('exp','repoint+9000');
		    			if(M('Member')->where($map)->save($user)){
		    				$this->success('新增订单成功！', U('index'));
		    			} else {
		    				$this->error('新增订单失败！', U('index'));
		    			}
		    		}
	    		} else {
	    			$this->error('余额不足,请联系公司充值！');
	    		}
    		} else { 
    			$this->error('您还有未通过审核的订单！');
    		}
    	} else{
    		$map['id'] = $id;
            $data = M('Order')->where($map)->find();
            $fields = get_model_attribute(5);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '订单修改';
            $this->assign('data', $data);
            $this->display();
    	}
    }

    /**
     * 删
     */
    public function changeStatus($method = null){
    	$id = array_unique((array)I('id',0));
    	$id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['id'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbidorder':
                $this->forbid('Order', $map );
                break;
            case 'resumeorder':
                $this->resume('Order', $map );
                break;
            case 'deleteorder':
            	$map['id'] = $id;
            	$num = M('Order')->where($map)->find();
            	if(intval($num['status']) > 0){
            		$this->error('订单已审核，不可修改');
            	} else {
	            	$this->delete('Order', $map );
	                break;
            	}
            default:
                $this->error('参数非法');
        }
    }

    /**
     * 改
     */
    public function edit($id = ''){
    	if(IS_POST){
	    	$mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
    		$map['id'] = $id;
			$data = M('order')->where($map)->find();
			if(!(is_administrator() || $group['group_id'] == 4) && $data['status']){
    			$this->error('订单审核后不可以修改！');
			}
	    	$order=D('order')->create();
    		if(!M('order')->where($map)->save($order)){
    			$this->error('更新失败！');
    		} else {
    			$this->success('更新成功！', U('index'));
    		}
    	} else {
	    	$mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
			if(is_administrator() || $group['group_id'] == 4){
				$kaka = 1;
			} else {
				$kaka = 0;
			}
	    	$map['id'] = $id;
			$data = M('order')->where($map)->find();
       		$fields = get_model_attribute(5);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '订单修改';
            $this->assign('data', $data);
            $this->assign('kaka', $kaka);
            $this->display();
    	}

    }

    public function adminEdit($id = '', $wow = ''){
    	if(IS_POST){
	    	$mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
    		$map['id'] = $id;
			$data = M('order')->where($map)->find();
			if(!(is_administrator() || $group['group_id'] == 4) && $data['status']){
    			$this->error('订单审核后不可以修改！');
			}
	    	$order=D('order')->create();
	    	if($order['status'] < $data['before_status']){
	    		$this->error('订单状态不可回退!');
	    	} else{
	    		$order['before_status'] = $order['status'];
	    	}
    		if(!M('order')->where($map)->save($order)){
    			$this->error('更新失败！');
    		} else {
    			if(intval($wow) == 1){
    				$order['whether'] = 1;
    				if(M('Order')->where($map)->save($order)){
    					if($this->changePoint($id,$order['price'])){
		    				$this->success('更新成功！', U('index'));	
		    			}  else {
		    				$this->error('更新失败!', U('index'));
		    			}
    				} else {
	    				$this->error('更新失败!', U('index'));
	    			}
    			} else {
    				$this->success('更新成功！', U('index'));
    			}
    		}
    	} else {
	    	$mapa['uid'] = intval(is_login());
			$group = M('AuthGroupAccess')->where($mapa)->find();
			if(is_administrator() || $group['group_id'] == 4){
				$kaka = 1;
			} else {
				$kaka = 0;
			}
	    	$map['id'] = $id;
			$data = M('order')->where($map)->find();
       		$fields = get_model_attribute(5);
            $this->assign('fields',$fields['1']);
            $this->meta_title = '订单修改';
            $this->assign('data', $data);
            $this->assign('kaka', $kaka);
            $this->display();
    	}

    }

    public function countOrder(){
    	$map['uid'] = is_login();
    	// $map['status'] = array(array('lt',1));
    	$map['status'] = 0;
    	$num = M('Order')->where($map)->count();
    	return $num;
    }

    public function exportdata(){
    	$map['id'] = array('in',I('id'));
    	$data = M('Order')->where($map)->select();

    	// foreach ($data as $key => $value) {
    	// 	$data[$key]['create_time'] = $value['create_time'] = data
    	// }
    	import("Org.Util.PHPExcel");
	    import("Org.Util.PHPExcel.Writer.Excel5");
	    import("Org.Util.PHPExcel.IOFactory.php");
	    $filename="export_excel";
	    $headArr=array("订单编号","性别","患者姓名","年龄","体重","电话","家族及个人病史","当下详细病情描述","检验数值及检查报告","用药及治疗情况","当下急需调理的问题","二次及以上定制情况（二次，三次，四次......）","病例报告和症状图片上传","下单人","订单状态","专家初审备注信息","客服回访备注信息","开方备注信息","划价备注信息","备料生产备注信息","生产包装备注信息","待发货备注信息");
	    $this->getExcel($filename,$headArr,$data);
    }

    private function getExcel($fileName,$headArr,$data){

	    //对数据进行检验
	    if(empty($data) || !is_array($data)){
	        die("data must be a array");
	    }
	    //检查文件名
	    if(empty($fileName)){
	        exit;
	    }
	    $date = date("Y_m_d",time());
	    $fileName .= "_{$date}.xls";
	    //创建PHPExcel对象，注意，不能少了\
	    $objPHPExcel = new \PHPExcel();
	    $objProps = $objPHPExcel->getProperties();

	    //设置表头
	    $key = ord("A");
	    foreach($headArr as $v){
	        $colum = chr($key);
	        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.'1', $v);
	        $key += 1;
	    }
	    $column = 2;
	    $objActSheet = $objPHPExcel->getActiveSheet();
	    foreach($data as $key => $rows){ //行写入
	        $span = ord("A");
	        foreach($rows as $keyName=>$value){// 列写入
	            $j = chr($span);
	            $objActSheet->setCellValue($j.$column, strip_tags(str_replace('&nbsp;','',$value)));
	            $span++;
	        }
	        $column++;
	    }
	    $fileName = iconv("utf-8", "gb2312", $fileName);
	    //重命名表
	    // $objPHPExcel->getActiveSheet()->setTitle('test');
	    //设置活动单指数到第一个表,所以Excel打开这是第一个表
	    $objPHPExcel->setActiveSheetIndex(0);
	    ob_end_clean();
	    ob_start();
	    header('Content-Type: application/vnd.ms-excel');
	    header("Content-Disposition: attachment;filename=\"$fileName\"");
	    header('Cache-Control: max-age=0');
	    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	    $objWriter->save('php://output'); //文件通过浏览器下载
	    exit;
	}

	public function changePoint($id = '', $price = ''){
		$mapo['id'] = $id;
		$data = M('Order')->where($mapo)->find();
		$mapm['uid'] = intval($data['uid']);
		$datam = M('Member')->where($mapm)->find();
		if($datam['point'] + 9000 > $price){
			$datam['point'] = $datam['point'] + 9000 - $price;
			$datam['repoint'] = $datam['repoint'] - 9000;
			$datam['total_money'] = array('exp', $datam['total_money'].'-'.$price);
			if(!M('Member')->where($mapm)->save($datam)){
				return false;
			} else {
				$this->addList($mapm['uid'], $price);
				return true;
			}
		} else {
			$this->error('账号余额不足！', U('index'));
		}
	}

	public function addList($uid = '', $price = ''){
        $create_time = date("Y-m-d H:i:s");
        $admin_id = is_login();
        $data = array('uid' => $uid, 'money' => '-'.$price, 'create_time' => $create_time, 'description' => '订单消费', 'admin_id' => $admin_id);
        if(!M('List')->add($data)){
            $this->error('充值失败!');
        } else {
            // $this->success('充值成功!');
        }
    }

}